<template>
  <a-modal :title="title"
           :visible="dialogShow"
           width="700px"
           height="500px"
           append-to-body
           :footer="null"
           @cancel="() => closeDialog(false)"
           destroyOnClose>
    <a-spin :spinning="spinning">
      <div class="dialog-content">
        <div class="dialog-content-header">
          <a-select placeholder="请选择机构分组名称"
                    showArrow
                    style="width: 100%"
                    v-model="value"
                    @change="groupChange">
            <a-option v-for="(item,index) in groupList"
                      :key="index"
                      :value="item.id">
              {{ item.name }}
            </a-option>
          </a-select>
        </div>
        <div class="dialog-content-body">
          <a-row :gutter="16"
                 type="flex">
            <a-col :span="14">
              <div class="dialog-content-unittree">
                <a-tree v-model="checkedKeysUnit"
                        checkable
                        :showIcon="true"
                        :autoExpandParent="autoExpandParent"
                        :expandedKeys="expandedKeys"
                        :selectedKeys="selectedKeys"
                        :load-data="loadTree"
                        :tree-data="treeDataUnit"
                        :checkStrictly="true"
                        @expand="onExpand"
                        @check="onCheck"
                        ref="unitTree">
                  <a-icon slot="switcherIcon"
                          type="caret-down" />
                  <a-icon slot="clazz"
                          type="appstore" />
                  <a-icon slot="unit"
                          type="home" />
                  <a-icon slot="dept"
                          type="bank" />
                  <template slot="custom"
                            slot-scope="item">
                    <span>{{ item.title }} </span>
                  </template>
                </a-tree>
              </div>
            </a-col>
            <a-col :span="10">
              <div class="dialog-content-unitbox">
                <div class="dialog-content-unitbox-dataItem"
                     v-for="(item,index) in selectData"
                     :key="index">
                  <a-tag closable
                         @click.prevent="onRemove(item,index)"
                         @close.prevent="onRemove(item,index)">
                    {{ item.title }}
                  </a-tag>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="dialog-content-btnbox">
          <a-button type="primary"
                    @click="onSubmit">确定</a-button>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { getUnitTreeNodesByParentId, getGroupList, getGroupAndUnitsById } from './../api/select'

import PropTypes from '@zh/common-utils/prop-types'
export default {
  name: 'ZUnitGroup',
  provide () {
    return {
      dialog: this
    }
  },
  props: {
    valueId: PropTypes.string.def('').des('机构分组id'),
    title: PropTypes.string.def('机构分组').des('弹窗标题')
  },
  model: {
    prop: 'valueId',
    event: 'input'
  },
  data () {
    return {
      value: null,
      dialogShow: false,
      spinning: false,
      groupList: [],
      selectData: [],
      // 机构树相关参数
      unitId: [], // 机构id
      treeDataUnit: [], // 机构树
      checkedKeysUnit: {
        // 选中的节点
        checked: [],
        halfChecked: []
      },
      autoExpandParent: false,
      expandedKeys: [],
      selectedKeys: []

    }
  },
  watch: {
    checkedKeysUnit: {
      handler (val) {
        this.unitId = val.checked
      }
    },
    valueId: {
      immediate: true,
      deep: true,
      handler (val) {
        this.value = val
      }
    }
  },
  methods: {
    openDialog () {
      this.dialogShow = true
      this.getUnitGroupList()
      this.loadTree()
    },
    closeDialog () {
      this.dialogShow = false
    },
    // 机构分组列表
    getUnitGroupList () {
      const page = {
        currPage: 1,
        pageSize: 1000
      }
      getGroupList(page).then(res => {
        this.groupList = res
        const arr = []
        res.map(item => {
          arr.push({
            id: item.groupsId,
            name: item.groupName
          })
        })
        this.groupList = arr
      })
    },
    // 根据分组id返回分组信息
    getInfoByid (id) {
      getGroupAndUnitsById(id).then(res => {
        const unitArr = []; const ids = []
        if (res.unitGroupsList.length > 0) { }
        res.unitGroupsList.forEach((item) => {
          ids.push(item.unitId)
          unitArr.push({
            value: item.unitId,
            title: item.unitName
          })
        })
        this.checkedKeysUnit.checked = ids
        this.unitId = ids
        this.selectData = unitArr
        // this.$refs.unitTree.$forceUpdate()
      })
    },
    // 分组切换
    groupChange (value) {
      this.value = value
      this.getInfoByid(value)
    },
    // 删除tag
    onRemove (item, index) {
      const that = this
      const rs = that.checkedKeysUnit.checked.findIndex((c) => c == item.value)
      const keys = [...that.checkedKeysUnit.checked]
      keys.splice(rs, 1)
      that.checkedKeysUnit.checked = keys
      that.selectData.splice(that.selectData.indexOf(item), 1)
    },
    // 机构树懒加载
    loadTree (treeNode) {
      const that = this
      const id = !treeNode ? 0 : treeNode.dataRef.value
      return new Promise((resolve) => {
        getUnitTreeNodesByParentId([{ id: id }])
          .then((res) => {
            const data = res.map((item) => {
              return {
                value: item.id,
                title: item.name,
                key: item.id,
                parentId: item.parentId,
                scopedSlots: {
                  title: 'custom',
                  icon: 'icon'
                }
              }
            })
            if (treeNode) {
              treeNode.dataRef.children = data
              that.treeDataUnit = [...that.treeDataUnit]
              resolve()
            } else {
              that.treeDataUnit = data
            }
          })
      })
    },
    // 点击复选框触发
    onCheck (checkedKeys, info) {
      this.checkedKeysUnit.checked = checkedKeys.checked
      if (info.checked) {
        const o = this.selectData.map((i) => {
          return i.value != info.node.value
        })
        if (o) {
          this.selectData.push({
            value: info.node.dataRef.value,
            title: info.node.dataRef.title
          })
        }
      } else {
        const o = []
        this.selectData.map((i) => {
          if (i.value != info.node.value) {
            o.push(i)
          }
        })
        this.selectData = o
      }
    },
    onExpand (expandedKeys, info) {
      this.autoExpandParent = false
      this.expandedKeys = expandedKeys
    },
    // 确定
    onSubmit () {
      const obj = {
        groupId: this.value,
        unitList: this.unitId
      }
      this.$emit('change', obj)
      this.$emit('input', obj)
      this.closeDialog()
    }
  }
}
</script>
<style lang="less" scoped>
.dialog-content {
  &-body {
    margin-top: 10px;
  }
  &-unittree {
    height: 300px;
    border: 1px solid #d9d9d9;
    overflow: auto;
  }
  &-unitbox {
    height: 300px;
    padding: 10px;
    border: 1px solid #d9d9d9;
    overflow-y: auto;
    &-dataItem {
      float: left;
      margin-right: 5px;
      // min-width: 200px;
      line-height: 30px;
      text-align: left;
    }
  }
  &-btnbox {
    margin-top: 20px;
    text-align: center;
  }
}
::v-deep .ant-btn span {
  margin-left: 0;
}
</style>
